package com.zhyl.demo.controller;

import com.zhyl.demo.entity.*;
import com.zhyl.demo.service.*;
import com.zhyl.demo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

/**
 * @author yang3
 */
@RestController
@RequestMapping("/theEnd")
public class TheEndController {
    private final TheEndService theEndService;
    private final AppointmentService appointmentService;
    private final ConsultationService consultationService;
    private final PrescriptionService prescriptionService;
    private final DoctorService doctorService;
    private final PatientService patientService;
    private final InHospitalService inHospitalService;
    private final SendMessageService sendMessageService;

    @Autowired
    private TheEndController(TheEndService theEndService,
                             AppointmentService appointmentService,
                             ConsultationService consultationService,
                             PrescriptionService prescriptionService,
                             DoctorService doctorService,
                             PatientService patientService,
                             InHospitalService inHospitalService,
                             SendMessageService sendMessageService) {
        this.theEndService = theEndService;
        this.appointmentService = appointmentService;
        this.consultationService = consultationService;
        this.prescriptionService = prescriptionService;
        this.doctorService = doctorService;
        this.patientService = patientService;
        this.inHospitalService = inHospitalService;
        this.sendMessageService = sendMessageService;
    }

    @RequestMapping("/addTheEnd")
    public Result addTheEnd(@RequestBody TheEnd theEnd) {
        if (theEnd == null) {
            return Result.error("参数错误");
        }

        Appointment appointment = appointmentService.getAppointmentDetail(theEnd.getAppointmentId());
        if (appointment == null) {
            return Result.error("预约信息不存在");
        }
        theEnd.setAppointment(appointment);

        Prescription prescription = prescriptionService.getPrescriptionDetail(theEnd.getPrescriptionId());
        if (prescription == null) {
            theEnd.setPrescription(null);
        }
        theEnd.setPrescription(prescription);
        double yuE = patientService.showInfo(theEnd.getPatientId()).getBalance();
        double yaoFei = 0;
        if (prescription!=null){
            yaoFei = prescription.getTotal();
        }

        double cha = yuE - (yaoFei);
        if (cha >= 0) {
            theEnd.setHavePay((double) 0);
            Patient patient = patientService.showInfo(theEnd.getPatientId());
            patient.setBalance(cha);
            patientService.updateInfo(patient);
            theEnd.setIsDone("已完成");
            SendMessage sendMessage = new SendMessage();
            sendMessage.setMessage("您已完成此次就诊，祝您生活愉快！");
            sendMessage.setUserId(theEnd.getPatientId());
            sendMessageService.sendMessage(sendMessage);
        } else {
            Patient patient = patientService.showInfo(theEnd.getPatientId());
            patient.setBalance(0.0);
            patientService.updateInfo(patient);
            theEnd.setHavePay(Math.abs(cha));
            theEnd.setIsDone("待用户支付");
            SendMessage sendMessage = new SendMessage();
            sendMessage.setMessage("您有一笔费用未支付，请及时支付");
            sendMessage.setUserId(theEnd.getPatientId());
            sendMessageService.sendMessage(sendMessage);
        }


        Boolean aBoolean = theEndService.addTheEnd(theEnd);
        if (aBoolean) {
            Boolean isComplete = appointmentService.completeAppointment(theEnd.getAppointmentId());
            if (isComplete) {
                return Result.success();
            } else {
                return Result.error("失败");
            }
        } else {
            return Result.error("添加失败");
        }
    }

    @RequestMapping("/getAll")
    public Result getAll() {
        ArrayList<TheEnd> all = theEndService.getAll();
        return getResult(all);
    }

    /**
     * 封装起来返回theEnd实例
     *
     * @param all
     * @return
     */
    private Result getResult(ArrayList<TheEnd> all) {
        if (all != null) {
            for (TheEnd item : all) {
                item.setAppointment(appointmentService.getAppointmentDetail(item.getAppointmentId()));
                item.setConsultation(consultationService.getConsultationDetail(item.getConsultationId()));
                item.setPrescription(prescriptionService.getPrescriptionDetail(item.getPrescriptionId()));
                item.setDoctor(doctorService.docInfo(item.getDoctorId()));
                item.setPatient(patientService.showInfo(item.getPatientId()));
            }
            return Result.success(all);
        } else {
            return Result.error("无数据");
        }
    }

    @RequestMapping("/getByDoc")
    public Result getByDoc(int docId) {
        if (docId <= 0) {
            return Result.error("参数错误");
        }
        ArrayList<TheEnd> byDoc = theEndService.getByDoc(docId);
        return getResult(byDoc);
    }

    @RequestMapping("/getByPatient")
    public Result getByPatient(int patientId) {
        if (patientId <= 0) {
            Result.error("参数错误");
        }
        ArrayList<TheEnd> byPatient = theEndService.getByPatient(patientId);
        return getResult(byPatient);
    }

    @RequestMapping("/searchPatient")
    public Result searchPatient(String patientName, int docId) {
        if (patientName == null || docId <= 0) {
            return Result.error("-1", "参数错误");
        }
        ArrayList<Patient> patients = patientService.searchInfo(patientName);
        if (patients == null) {
            return Result.success();
        }
        ArrayList<TheEnd> searchList = new ArrayList<>();
        for (Patient item : patients) {
            ArrayList<TheEnd> theEnds = theEndService.searchPatient(item.getPatid(), docId);
            for (TheEnd theEnd : theEnds) {
                theEnd.setPatient(item);
                theEnd.setDoctor(doctorService.docInfo(docId));
                theEnd.setConsultation(consultationService.getConsultationDetail(theEnd.getConsultationId()));
                theEnd.setAppointment(appointmentService.getAppointmentDetail(theEnd.getAppointmentId()));
                theEnd.setPrescription(prescriptionService.getPrescriptionDetail(theEnd.getPrescriptionId()));
                searchList.add(theEnd);
            }
        }

        if (searchList.get(0) != null) {
            return Result.success(searchList);
        } else {
            return Result.error("-1", "无该患者");
        }
    }

    @RequestMapping("/adminSearchPatient")
    public Result adminSearchPatient(String patientName) {
        if (patientName == null ) {
            return Result.error("-1", "参数错误");
        }
        ArrayList<Patient> patients = patientService.searchInfo(patientName);
        if (patients == null) {
            return Result.success();
        }
        ArrayList<TheEnd> searchList = new ArrayList<>();
        for (Patient item : patients) {
            ArrayList<TheEnd> theEnds = theEndService.adminSearchPatient(item.getPatid());
            if (!item.getName().isEmpty()) {
                for (TheEnd theEnd : theEnds) {
                    theEnd.setPatient(item);
                    theEnd.setConsultation(consultationService.getConsultationDetail(theEnd.getConsultationId()));
                    theEnd.setAppointment(appointmentService.getAppointmentDetail(theEnd.getAppointmentId()));
                    theEnd.setPrescription(prescriptionService.getPrescriptionDetail(theEnd.getPrescriptionId()));
                    searchList.add(theEnd);
                }
            }
        }

        if (searchList.get(0) != null) {
            return Result.success(searchList);
        } else {
            return Result.error("-1", "无该患者");
        }
    }

    @RequestMapping("/checkCaseHistoryByPatient")
    public Result checkCaseHistoryByPatient(int theEndId) {
        if (theEndId<=0){
            return Result.error("-1","参数错误");
        }
        TheEnd theEndDetail = theEndService.getTheEndDetail(theEndId);
        int patId = theEndDetail.getPatientId();
        int docId = theEndDetail.getDoctorId();
        ArrayList<TheEnd> theEnds = theEndService.searchPatientIlls(patId, docId);
        if (theEnds == null) {
            return Result.error("-1", "暂无数据");
        } else {
            for (TheEnd theEnd : theEnds) {
                theEnd.setPatient(patientService.showInfo(patId));
                theEnd.setDoctor(doctorService.docInfo(docId));
                theEnd.setConsultation(consultationService.getConsultationDetail(theEnd.getConsultationId()));
                theEnd.setAppointment(appointmentService.getAppointmentDetail(theEnd.getAppointmentId()));
                theEnd.setPrescription(prescriptionService.getPrescriptionDetail(theEnd.getPrescriptionId()));
            }
        }
        return Result.success(theEnds);
    }


    @RequestMapping("/checkCaseHistoryByAppointment")
    public Result checkCaseHistoryByAppointment(int appointmentId) {
        if (appointmentId <= 0) {
            return Result.error("-1", "参数错误");
        }
        Appointment appointmentDetail = appointmentService.getAppointmentDetail(appointmentId);
        TheEnd theEnd = theEndService.checkCaseHistoryByAppointment(appointmentId);
        if (theEnd == null) {
            return Result.error("-1", "暂无诊断信息");
        }
        theEnd.setPatient(patientService.showInfo(appointmentDetail.getPatientId()));
        theEnd.setDoctor(doctorService.docInfo(appointmentDetail.getDoctorId()));
        theEnd.setConsultation(consultationService.getConsultationDetail(theEnd.getConsultationId()));
        theEnd.setAppointment(appointmentService.getAppointmentDetail(theEnd.getAppointmentId()));
        theEnd.setPrescription(prescriptionService.getPrescriptionDetail(theEnd.getPrescriptionId()));
        return Result.success(theEnd);

    }

    @RequestMapping("/theEndDetail")
    public Result theEndDetail(int theEndId) {

        if (theEndId <= 0) {
            return Result.error("-1", "参数错误");
        }
        TheEnd theEndDetail = theEndService.getTheEndDetail(theEndId);
        if (theEndDetail == null) {
            return Result.error("-1", "暂无数据");
        }
        theEndDetail.setPatient(patientService.showInfo(theEndDetail.getPatientId()));
        theEndDetail.setDoctor(doctorService.docInfo(theEndDetail.getDoctorId()));
        theEndDetail.setConsultation(consultationService.getConsultationDetail(theEndDetail.getConsultationId()));
        theEndDetail.setAppointment(appointmentService.getAppointmentDetail(theEndDetail.getAppointmentId()));
        theEndDetail.setPrescription(prescriptionService.getPrescriptionDetail(theEndDetail.getPrescriptionId()));
        return Result.success(theEndDetail);
    }

    @RequestMapping("/toPay")
    public Result toPay(Integer theEndId,Integer patId) {

        if (theEndId==null || patId==null) {
            return Result.error("-1", "参数错误");
        }
        TheEnd theEndDetail = theEndService.getTheEndDetail(theEndId);
        Double havePay = theEndDetail.getHavePay();
        Patient patient = patientService.showInfo(patId);
        if (patient.getBalance() < havePay) {
            return Result.error("-1", "余额不足");
        }
        patient.setBalance(patient.getBalance() - havePay);
        Boolean b = patientService.updateInfo(patient);
        if (b) {
            theEndDetail.setHavePay(0.0);
            theEndDetail.setIsDone("已完成");
            Boolean b1 = theEndService.updateInfo(theEndDetail);
            if (b1){
                SendMessage sendMessage = new SendMessage();
                sendMessage.setMessage("您已完成此次就诊，祝您生活愉快！");
                sendMessage.setUserId(patient.getPatid());
                sendMessageService.sendMessage(sendMessage);
            }
            return Result.success("支付成功");
        }
            return Result.error("-1", "支付失败");

    }

    @RequestMapping("/checkIsHave")
    public Result checkIsHave(Integer appointmentId) {

        if (appointmentId==null) {
            return Result.error("-1", "参数错误");
        }
        TheEnd theEnd = theEndService.checkCaseHistoryByAppointment(appointmentId);
        if (theEnd == null) {
            return Result.error("-1", "暂无数据");
        }
        return Result.success(theEnd);
    }

}
